# admin.py
from flask import Blueprint, render_template, jsonify, request, redirect, url_for
from flask_login import login_required, current_user
from .app import db, socketio
from .models import Announcement, Survey, Feedback, User, AdminRequest, FeedbackResponse, SurveyResponse
from datetime import datetime

admin_bp = Blueprint('admin', __name__)

@admin_bp.route('/admin/dashboard')
@login_required
def admin_dashboard():
    if current_user.role != '管理员':
        return redirect(url_for('user.dashboard'))
    return render_template('admin_dashboard.html')

@admin_bp.route('/api/announcements', methods=['POST'])
@login_required
def create_announcement():
    try:
        if current_user.role != '管理员':
            return jsonify({'success': False, 'message': '权限不足'}), 403
        
        data = request.get_json()

        if not data:
            return jsonify({'success': False, 'message': '请求数据为空'}), 400
        
        if 'title' not in data or 'content' not in data:
            return jsonify({'success': False, 'message': '标题和内容是必填字段'}), 400
        
        new_announcement = Announcement(
            title=data['title'],
            content=data['content']
        )
        db.session.add(new_announcement)
        db.session.commit()

        socketio.emit('new_announcement', {
            'id': new_announcement.id,
            'title': new_announcement.title,
            'content': new_announcement.content,
            'created_at': new_announcement.created_at.strftime('%Y-%m-%d %H:%M')
        })

        return jsonify({'success': True, 'id': new_announcement.id})

    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'发布公告失败: {str(e)}'}), 500

@admin_bp.route('/api/surveys', methods=['POST'])
@login_required
def create_survey():
    if current_user.role != '管理员':
        return jsonify({'success': False, 'message': '权限不足'}), 403
    
    data = request.get_json()
    new_survey = Survey(
        title=data['title'],
        content=data['content']
    )
    db.session.add(new_survey)
    db.session.commit()
    
    socketio.emit('new_survey', {
        'id': new_survey.id,
        'title': new_survey.title,
        'content': new_survey.content,
        'created_at': new_survey.created_at.strftime('%Y-%m-%d %H:%M')
    })
    
    return jsonify({'success': True, 'id': new_survey.id})

@admin_bp.route('/api/users')
@login_required
def get_users():
    if current_user.role != '管理员':
        return jsonify({'success': False, 'message': '权限不足'}), 403
    
    users = User.query.order_by(User.created_at.desc()).all()
    return jsonify([{
        'id': u.id,
        'username': u.username,
        'role': u.role,
        'created_at': u.created_at.strftime('%Y-%m-%d %H:%M')
    } for u in users])

@admin_bp.route('/api/users/<int:user_id>', methods=['DELETE'])
@login_required
def delete_user(user_id):
    if current_user.role != '管理员':
        return jsonify({'success': False, 'message': '权限不足'}), 403
    
    user = User.query.get(user_id)
    if user:
        db.session.delete(user)
        db.session.commit()
        return jsonify({'success': True})
    return jsonify({'success': False, 'message': '用户不存在'}), 404

@admin_bp.route('/api/admin_requests/<int:request_id>', methods=['PUT'])
@login_required
def update_admin_request(request_id):
    try:
        if current_user.role != '管理员':
            return jsonify({'success': False, 'message': '权限不足'}), 403
        
        data = request.get_json()
        if not data:
            return jsonify({'success': False, 'message': '请求数据为空'}), 400
        
        status = data.get('status')
        if not status:
            return jsonify({'success': False, 'message': '缺少状态参数'}), 400
        
        admin_request = AdminRequest.query.get(request_id)
        if not admin_request:
            return jsonify({'success': False, 'message': '申请不存在'}), 404
        
        admin_request.status = status
        
        if status == 'approved':
            user = User.query.get(admin_request.user_id)
            if not user:
                return jsonify({'success': False, 'message': '用户不存在'}), 404
            user.role = '管理员'
        
        db.session.commit()
        
        # 通知用户申请状态更新
        if status == 'approved':
            socketio.emit('admin_request_approved', {
                'id': admin_request.id
            }, room=f'user_{admin_request.user_id}')
        elif status == 'rejected':
            socketio.emit('admin_request_rejected', {
                'id': admin_request.id
            }, room=f'user_{admin_request.user_id}')
        
        return jsonify({'success': True})
    
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'处理失败: {str(e)}'}), 500

@admin_bp.route('/api/admin_requests')
@login_required
def get_admin_requests():
    try:
        if current_user.role != '管理员':
            return jsonify({'success': False, 'message': '权限不足'}), 403
        
        # 添加关联查询获取用户名
        requests = db.session.query(
            AdminRequest.id,
            AdminRequest.user_id,
            AdminRequest.reason,
            AdminRequest.status,
            AdminRequest.created_at,
            User.username
        ).join(User, AdminRequest.user_id == User.id).order_by(AdminRequest.created_at.desc()).all()
        
        return jsonify([{
            'id': r.id,
            'user_id': r.user_id,
            'username': r.username,
            'reason': r.reason,
            'status': r.status,
            'created_at': r.created_at.strftime('%Y-%m-%d %H:%M')
        } for r in requests])
    
    except Exception as e:
        print(f"获取管理员申请失败: {str(e)}")
        return jsonify({'success': False, 'message': f'获取申请失败: {str(e)}'}), 500

@admin_bp.route('/api/survey_responses')
@login_required
def get_survey_responses():
    if current_user.role != '管理员':
        return jsonify({'success': False, 'message': '权限不足'}), 403
    
    responses = SurveyResponse.query.join(User).join(Survey).order_by(SurveyResponse.created_at.desc()).all()
    return jsonify([{
        'id': r.id,
        'survey_id': r.survey_id,
        'survey_title': r.survey.title,
        'user_id': r.user_id,
        'username': r.user.username,
        'content': r.response,  # 使用 response 字段
        'created_at': r.created_at.strftime('%Y-%m-%d %H:%M')
    } for r in responses])

@admin_bp.route('/api/feedbacks')
@login_required
def get_feedbacks():
    try:
        if current_user.role != '管理员':
            return jsonify({'success': False, 'message': '权限不足'}), 403
        
        # 获取所有反馈，包括用户信息
        feedbacks = db.session.query(
            Feedback.id,
            Feedback.content,
            Feedback.status,
            Feedback.created_at,
            User.username
        ).join(User, Feedback.user_id == User.id).order_by(Feedback.created_at.desc()).all()
        
        return jsonify([{
            'id': f.id,
            'content': f.content,
            'status': f.status,
            'created_at': f.created_at.strftime('%Y-%m-%d %H:%M'),
            'username': f.username
        } for f in feedbacks])
    
    except Exception as e:
        print(f"获取反馈失败: {str(e)}")
        return jsonify({'success': False, 'message': f'获取反馈失败: {str(e)}'}), 500

@admin_bp.route('/api/feedbacks/<int:feedback_id>')
@login_required
def get_feedback_detail(feedback_id):
    try:
        if current_user.role != '管理员':
            return jsonify({'success': False, 'message': '权限不足'}), 403
        
        # 获取反馈详情
        feedback = db.session.query(
            Feedback.id,
            Feedback.content,
            Feedback.status,
            Feedback.created_at,
            User.username
        ).join(User, Feedback.user_id == User.id).filter(Feedback.id == feedback_id).first()
        
        if not feedback:
            return jsonify({'success': False, 'message': '反馈不存在'}), 404
        
        # 获取所有回复
        responses = FeedbackResponse.query.filter_by(feedback_id=feedback_id).all()
        
        return jsonify({
            'id': feedback.id,
            'content': feedback.content,
            'status': feedback.status,
            'username': feedback.username,
            'created_at': feedback.created_at.strftime('%Y-%m-%d %H:%M'),
            'responses': [{
                'id': r.id,
                'content': r.content,
                'created_at': r.created_at.strftime('%Y-%m-%d %H:%M')
            } for r in responses]
        })
    
    except Exception as e:
        print(f"获取反馈详情失败: {str(e)}")
        return jsonify({'success': False, 'message': f'获取反馈详情失败: {str(e)}'}), 500

@admin_bp.route('/api/feedback_responses', methods=['POST'])
@login_required
def create_feedback_response():
    try:
        if current_user.role != '管理员':
            return jsonify({'success': False, 'message': '权限不足'}), 403
        
        data = request.get_json()
        feedback_id = data.get('feedback_id')
        content = data.get('content')
        
        if not feedback_id or not content:
            return jsonify({'success': False, 'message': '反馈ID和内容不能为空'}), 400
        
        # 检查反馈是否存在
        feedback = Feedback.query.get(feedback_id)
        if not feedback:
            return jsonify({'success': False, 'message': '反馈不存在'}), 404
        
        # 创建回复
        new_response = FeedbackResponse(
            feedback_id=feedback_id,
            content=content
        )
        db.session.add(new_response)
        
        # 更新反馈状态为已处理
        feedback.status = 'processed'
        
        db.session.commit()
        
        # 通知用户
        socketio.emit('feedback_processed', {
            'feedback_id': feedback_id,
            'response_id': new_response.id
        }, room=f'user_{feedback.user_id}')
        
        return jsonify({'success': True, 'id': new_response.id})
    
    except Exception as e:
        db.session.rollback()
        print(f"创建反馈回复失败: {str(e)}")
        return jsonify({'success': False, 'message': f'创建回复失败: {str(e)}'}), 500